package com.boarsoft.boar.code.bean.biz.impl;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.code.bean.biz.BeanPropTreeBiz;
import com.boarsoft.boar.code.entity.BeanInfo;
import com.boarsoft.boar.code.entity.BeanPropTree;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("beanPropTreeBiz")
public class BeanPropTreeBizImpl extends SimpleBizImpl implements BeanPropTreeBiz {

	/**
	 * bean信息查询：/code/bean/info/list.do
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<BeanPropTree> list(String beanId, int pageNo, int pageSize) {

		StringBuilder sb = new StringBuilder();
		sb.append(" from BeanPropTree r where 1=1");
		if (Util.strIsNotEmpty(beanId)) {
			sb.append(" and r.beanId like '%").append(beanId).append("%'");
		}
		sb.append(" order by r.id");
		List<BeanPropTree> lt = this.dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<BeanPropTree>(lt.size(), lt, pageNo, pageSize);
	}

	/**
	 * bean类型名列表查询：/code/bean/info/find.do
	 */
	@Transactional(readOnly = true)
	@Override
	public ReplyInfo<Object> find(int pageNo, int pageSize) {
		return new ReplyInfo<>(true, new PagedResult<>(dao.getTotal("select count(*) from BeanInfo"),
				dao.list(BeanInfo.class, "and 1=1"), pageNo, pageSize));
	}

	/**
	 * 保存bean信息
	 * 
	 * @param beanPropTree
	 *            bean属性信息
	 * @return 存储数据库的key
	 */
	@Transactional
	@Override
	public String save(BeanPropTree beanPropTree) {
		return (String) this.dao.save(beanPropTree);
	}

	/**
	 * bean属性列表查询
	 */

	@Transactional(readOnly = true)
	@Override
	public List<BeanPropTree> findBeanPropByBeanId(String beanId, String key, String path) {
		StringBuilder sb = new StringBuilder();
		sb.append(" and beanId = '").append(beanId).append("'");
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (name like '%").append(key).append("%'").append(" or type like '%").append(key).append("%')");
		}
		if (Util.strIsNotEmpty(path)) {
			sb.append(" and path = '").append(path).append("'");
		}
		String sql = "select r from BeanPropTree r where 1=1".concat(sb.toString());
		return this.dao.list(sql);
	}

	@Override
	@Transactional
	public void delete(String id) {
		String w = String.format("and id='%s'", id);
		BeanPropTree beanPropTree = this.dao.find(BeanPropTree.class, w);
		if (beanPropTree != null) {
			this.dao.delete(beanPropTree);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public List<BeanPropTree> findBeanPropByType(String type) {
		StringBuilder sb = new StringBuilder();
		if (Util.strIsNotEmpty(type)) {
			sb.append(" and type like '%").append(type).append("%'");
		}
		return this.dao.list("select r from BeanPropTree r where 1=1".concat(sb.toString()));
	}
}
